import 'package:flutter/animation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/event/WkEventListener.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';

import '../../../blt/BltManager.dart';
import '../../../blt/RobotCommands.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../routes/app_pages.dart';
import '../../../storage/StorageManager.dart';
import '../../../widget/tips.dart';
import '../../DeviceConnection/controllers/device_connection_controller.dart';

class ManualConnectionController extends GetxController  {

  var scanDevicesMap = RxMap();
  AnimationController? animationController;

  var noFoundDevice = false.obs;

  @override
  void onInit() {
    super.onInit();


  }

  @override
  void onReady() {
    super.onReady();
    toScanning();
  }

  void toScanning () {
    scanDevicesMap.value.clear();

    BltManager.instance.toScan(dataCallBack: DataCallBack(
        deviceCallBack: (mapItem) {
        },errorCallBack: (tips) {
           noFoundDevice.value = true;

        }
    ),timeout: 60,deviceMap: scanDevicesMap,justScan: true);
  }

  @override
  void onClose() {
    super.onClose();

    Tips.dismissLoading();
  }

  void connectDeviceByManual(String deviceKey) async {
    String robotUserId = 'unknow_identity';
    List<String> robotUserIds = deviceKey.split('_');
    if (robotUserIds.length == 2) {
      robotUserId = robotUserIds[1];
    } else {
      robotUserId = deviceKey;
    }

    Tips.showLoading();

    await Future.delayed(Duration(seconds: 2));


    BluetoothDevice bluetoothDevice = scanDevicesMap[deviceKey]! as BluetoothDevice;
    BltManager.instance.connectDeviceManual(bluetoothDevice, robotUserId,dataCallBack: DataCallBack(
       deviceCallBack: (data) {
         Tips.dismissLoading();
         StorageManager.getStorage().write(AppConst.BLT_DEVICE_SN_CURRENTLY_TMP, robotUserId);

         DeviceConnectionController deviceConnectionController =  GetInstance().find<DeviceConnectionController>();
         deviceConnectionController.setAutoOrManualConnected(false);

         Get.toNamed(Routes.CONNECT_SUCESS);
       },
       errorCallBack: (error) {
         Tips.dismissLoading();
         CommonWidgets.showSingleBtnDialog(Get.context!, '', '蓝牙连接超时', WkEventListener(
           onClick: (v) {
                BltManager.instance.disConnectDevice();
           }
         ));
         // Tips.showToast('连接失败,请重新尝试.');
       }
    ), isNeedShowTips: true);
  }


}
